/**
 * 微信相关功能 Composable
 */
import { computed, ref } from 'vue'
import { useAppStore } from '../store/app'
import {
  type WechatJSSDKConfig,
  type WechatShareConfig,
  canUseWechatPay,
  configWechatShare,
  initWechatJSSDK,
  setWechatTitle,
} from '../utils/wechat'

export function useWechat() {
  const appStore = useAppStore()

  const isJSSDKReady = ref(false)
  const jssdkError = ref<string | null>(null)
  const isJSSDKLoaded = ref(false)

  // 计算属性
  const isWechatBrowser = computed(() => appStore.platformInfo.wechat.isWechatBrowser)
  const isWechatMiniProgram = computed(() => appStore.platformInfo.wechat.isWechatMiniProgram)
  const isWechatEnvironment = computed(() => appStore.platformInfo.wechat.isWechatEnvironment)
  const wechatVersion = computed(() => appStore.platformInfo.wechat.version)
  const canUseJSSDK = computed(() => appStore.platformInfo.wechat.canUseJSSDK)
  const canPay = computed(() => canUseWechatPay())

  // 检查JSSDK脚本加载状态
  const checkJSSDKLoaded = () => {
    // #ifdef H5
    if (typeof window !== 'undefined') {
      // 优先检查保存的原始微信JS-SDK对象
      // @ts-expect-error _wxOriginal is set by WeChat JS-SDK loading
      if (window._wxOriginal && typeof window._wxOriginal.config === 'function') {
        isJSSDKLoaded.value = true
        return true
      }
      // 备用检查：检查wx对象是否为微信JS-SDK（而不是uni-app的wx）
      if ('wx' in window) {
        // @ts-expect-error wx is provided by WeChat JS-SDK
        if (typeof wx.config === 'function') {
          isJSSDKLoaded.value = true
          return true
        }
      }
    }
    // #endif

    isJSSDKLoaded.value = false
    return false
  }

  // 初始化微信JS-SDK
  const initJSSDK = async (config: WechatJSSDKConfig) => {
    try {
      await initWechatJSSDK(config)
      isJSSDKReady.value = true
      jssdkError.value = null
      appStore.updateWechatJSSDKStatus(true)
      return true
    }
    catch (error: any) {
      isJSSDKReady.value = false
      jssdkError.value = error.message || '初始化失败'
      appStore.updateWechatJSSDKStatus(false)
      return false
    }
  }

  // 配置分享
  const configShare = (config: WechatShareConfig) => {
    if (!isWechatBrowser.value || !isJSSDKReady.value) {
      console.warn('当前环境不支持微信分享或JS-SDK未就绪')
      return
    }

    configWechatShare(config)
  }

  // 设置标题
  const setTitle = (title: string) => {
    setWechatTitle(title)
  }

  // 检查功能支持
  const checkSupport = () => {
    // 动态检查JSSDK加载状态
    checkJSSDKLoaded()

    return {
      isWechatBrowser: isWechatBrowser.value,
      isWechatMiniProgram: isWechatMiniProgram.value,
      isWechatEnvironment: isWechatEnvironment.value,
      canUseJSSDK: canUseJSSDK.value,
      canPay: canPay.value,
      isJSSDKReady: isJSSDKReady.value,
      isJSSDKLoaded: isJSSDKLoaded.value,
    }
  }

  return {
    // 状态
    isJSSDKReady,
    isJSSDKLoaded,
    jssdkError,

    // 计算属性
    isWechatBrowser,
    isWechatMiniProgram,
    isWechatEnvironment,
    wechatVersion,
    canUseJSSDK,
    canPay,

    // 方法
    initJSSDK,
    configShare,
    setTitle,
    checkSupport,
    checkJSSDKLoaded,
  }
}
